package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryList() {
        List<String> shoplist = stringRedisTemplate.opsForList().range("shoplist", 0, -1);
        if(shoplist.size()!=0){//从redis缓存中找到了
            List<ShopType> shopTypeList = shoplist.stream().map(obj -> {
                ShopType shopType = JSONUtil.toBean(obj, ShopType.class);
                return shopType;
            }).collect(Collectors.toList());
            return shopTypeList;
        }
        //从数据库当中查找
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        //查找后放到redis
        for (ShopType shopType : shopTypeList) {
            stringRedisTemplate.opsForList().rightPush("shoplist",JSONUtil.toJsonStr(shopType));
        }
        return shopTypeList;
    }
}
